package com.pdwbdn.utils;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;

import java.sql.Connection;
import java.sql.DriverManager;

public class DbConnUtil {
    public static Connection getConn(String database) {
        try {
            PropertiesConfiguration config = new PropertiesConfiguration("dnf-launcher.properties");
            String dbHost = config.getString("database.host");
            int dbPort = config.getInt("database.port", 3306);
            String dbUser = config.getString("database.user");
            String dbPassword = config.getString("database.password");
            if (dbHost == null || dbHost.isEmpty() ||
                    dbUser == null || dbUser.isEmpty() ||
                    dbPassword == null || dbPassword.isEmpty()) {
                return null;
            }
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + database + "?useUnicode=true&characterEncoding=latin1&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8";
            Connection connection = DriverManager.getConnection(url, dbUser, dbPassword);
            connection.setAutoCommit(false);
            connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
            return connection;
        } catch (Throwable t) {
            System.err.println(t.toString());
            return null;
        }
    }
}
